package com.xgr.wonderful.utils;

import java.io.File;
import java.io.UnsupportedEncodingException;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.xgr.wonderful.constant.Constant;
import com.xgr.wonderful.constant.HttpGetUrl;
import com.xgr.wonderful.constant.HttpPostUrl;
import com.xgr.wonderful.constant.URLConstant;

public class HttpProxy {

	private IHttpRequestListener mHttpRequestListener = null;
	
	public void setHttpRequestListener(IHttpRequestListener listener) {
		mHttpRequestListener = listener;
	}
	// 注册新用户
	// 参数data由调用者提供
	// 这里应该是一个User1对象的经过json序列化过的字符串
	public void registerUser(String data , IHttpRequestListener listener) {
		setHttpRequestListener(listener) ;
		
		doRealHttpRequest(HttpMethod.POST, HttpPostUrl.addUser(), null, data,
				null);
	}

	// 更新用户
	public void updateUser(String data , IHttpRequestListener listener) {
		setHttpRequestListener(listener) ;
		doRealHttpRequest(HttpMethod.POST, HttpPostUrl.updateUser(),
				LocalUserUtils.getInstance().getLocalUserToken(), data, null);
	}

	
	public void queryUserByUserID(String url , IHttpRequestListener listener){
		setHttpRequestListener(listener) ;
		doRealHttpRequest(HttpMethod.GET, url, null, null, null);
	}
	
	/**
	 * by lsj 
	 * @param deviceid
	 * @param listener
	 */
	public void getUserByDeviceid (String deviceid, IHttpRequestListener listener){
		setHttpRequestListener(listener) ;
		
		String url =HttpGetUrl.GetUserByDeviceId() +"?deviceid="+deviceid ;
		doRealHttpRequest(HttpMethod.GET, url, null, null, null) ;
	}

	/**
	 * 发表状态 by lsj 
	 * @param data
	 * @param listener
	 */
	public void publishStatus(String data, IHttpRequestListener listener) {
		setHttpRequestListener(listener) ;
		
		doRealHttpRequest(HttpMethod.POST, HttpPostUrl.PublishStatus(),
				LocalUserUtils.getInstance().getLocalUserToken(), data, null);
	}

	/**
	 * by lsj 
	 * @param data
	 * @param listener
	 */
	public void queryStatus(String data , IHttpRequestListener listener) {
		setHttpRequestListener(listener) ;
		doRealHttpRequest(HttpMethod.GET, HttpGetUrl.QueryStatus(),
				LocalUserUtils.getInstance().getLocalUserToken(), data, null);
	}
	
	/**
	 * 
	 * @param data
	 * @param listener
	 */
	public void queryStatusByID(String statusid, IHttpRequestListener listener) {
		setHttpRequestListener(listener) ;
		String url = HttpGetUrl.GetStatusByID()+"?id="+statusid;
		doRealHttpRequest(HttpMethod.GET,url,
				LocalUserUtils.getInstance().getLocalUserToken(), null, null);
	}

	
	/**
	 * by lsj 
	 * @param data
	 * @param listener
	 */
	public void queryCommentedStatus(String data, IHttpRequestListener listener) {
		setHttpRequestListener(listener) ;
		doRealHttpRequest(HttpMethod.GET, HttpGetUrl.QueryCommentedStatus(), 
				LocalUserUtils.getInstance().getLocalUserToken(), data, null);
	}
	

	/**
	 * by lsj 
	 * @param data
	 * @param listener
	 */
	public void publishComment(String data, IHttpRequestListener listener) {
		setHttpRequestListener(listener) ;
		
		doRealHttpRequest(HttpMethod.POST, HttpPostUrl.Comment(),
				LocalUserUtils.getInstance().getLocalUserToken(), data, null);
	}

	
	/**
	 * 查询评论，是看一条状态的评论时候用的
	 * @param data
	 * @param listener
	 */
	public void queryComment(String data, IHttpRequestListener listener) {
		setHttpRequestListener(listener) ;
		
		doRealHttpRequest(HttpMethod.GET, HttpPostUrl.QueryComment(),
				LocalUserUtils.getInstance().getLocalUserToken(), data, null);
	}
	
	/**
	 * by lsj 
	 * @param file
	 * @param listener
	 */
	public void uploadFile(File file, IHttpRequestListener listener) {
		setHttpRequestListener(listener) ;
		
		doRealHttpRequest(HttpMethod.POST, URLConstant.FileServerAddressProxy,
				LocalUserUtils.getInstance().getLocalUserToken(), null, file);
	}
	/**
	 * by lsj 
	 * @param data
	 * @param listener
	 */
	public void getLikeRelations(String data , IHttpRequestListener listener) {
		setHttpRequestListener(listener) ;
		
		doRealHttpRequest(HttpMethod.GET, HttpGetUrl.GetLikeRelations(), 
				LocalUserUtils.getInstance().getLocalUserToken(), data, null);
	}
	// 点赞
	public void doLikeAction(String data) {
		doRealHttpRequest(HttpMethod.POST, HttpPostUrl.Up(), LocalUserUtils
				.getInstance().getLocalUserToken(), data, null);
	}
	
	/**
	 * by lsj 
	 * @param data
	 * @param listener
	 */
	public void doLikeAction(String data , IHttpRequestListener listener) {
		setHttpRequestListener(listener) ;
		
		doRealHttpRequest(HttpMethod.POST, HttpPostUrl.Up(), LocalUserUtils
				.getInstance().getLocalUserToken(), data, null);
	}
	// 参数：
	// token：用户的token，只有注册的时候才能为空，其他情况下不能为空
	// data：要post的对象经过json序列化之后的字符串
	// file：要上传的文件，如果为空表示不上传文件
	private void doRealHttpRequest(HttpMethod method, String url, String token,
			String data, File file) {
		HttpUtils http = new HttpUtils();
		RequestParams params = new RequestParams();
		if (token != null) {
			params.addHeader(Constant.HTTP_REQUEST_HEADER_TOKEN, token);
		}
		if (data != null) {
			try {
				params.setBodyEntity(new StringEntity(data,
						Constant.HTTP_REQUEST_CHARSET));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		if (file != null) {
			params.addBodyParameter(Constant.HTTP_REQUEST_BODY_FILE, file);
		}
		http.configCurrentHttpCacheExpiry(0);
		http.send(method, url, params, new RequestCallBack<String>() {
			@Override
			public void onStart() {
				if (mHttpRequestListener != null) {
					mHttpRequestListener.OnHttpRequestStart();
				}
			}

			@Override
			public void onFailure(HttpException error, String msg) {
				error.printStackTrace();
				LogUtils.i(TAG, " fail msg:"+msg); 
				if (mHttpRequestListener != null) {
					mHttpRequestListener.OnHttpRequestFailure(msg);
				}
			}

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				if (mHttpRequestListener != null) {
					int errorCode = -1;
					String status = null;
					String dataJson = null;
					String infoJson = null;
					JSONObject result = null;
					try {
						// Creates a new JSONObject with name/value mappings
						// from the JSON string.
						result = new JSONObject(responseInfo.result);
						LogUtils.i(TAG, " success result:"+result); 
						status = result
								.optString(Constant.HTTP_REQUEST_RESULT_STATUS);
						errorCode = new Gson().fromJson(status, int.class);
						if (errorCode == Constant.ERR_HTTP_REQUEST_SUCCESS) {
							dataJson = result
									.optString(Constant.HTTP_REQUEST_RESULT_DATA);
							mHttpRequestListener
									.OnHttpRequestSuccessful(dataJson,
											Constant.ERR_HTTP_REQUEST_SUCCESS);
						} else {
							infoJson = result
									.optString(Constant.HTTP_REQUEST_RESULT_INFO);
							mHttpRequestListener
									.OnHttpRequestSuccessful(infoJson,
											Constant.ERR_HTTP_REQUEST_FAILURE);
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			}
		});
	}
	
	private static final String TAG ="HttpProxy" ; 
	public interface IHttpRequestListener {
		void OnHttpRequestStart();
		/**
		 * 链接网络成功，但是不一定返回正确的result 
		 */
		void OnHttpRequestSuccessful(String result, int errCode);
		/**
		 * 连接网络失败
		 */
		void OnHttpRequestFailure(String info);
	}
}
